package com.by.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.by.block.OrderBlockHandler;
import com.by.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class OrderController {
   @Autowired
   OrderService orderService;
   //blockHandler = "queryFail", blockHandlerClass = {OrderBlockHandler.class},
   // 发现写限流走限流,不写限流走降级,限流和降级只是把请求转到其他方法而不去处理业务方法
    @SentinelResource(value = "订单",blockHandler = "queryFail", blockHandlerClass = {OrderBlockHandler.class}, fallback = "handlerError", fallbackClass = {OrderBlockHandler.class}, exceptionsToIgnore = {NullPointerException.class})
    @GetMapping("/order")
    public Map query(int id) {
        System.out.println("订单id:::" + id);
        //int i = 8 / id;异常可以模拟降级方法
        return orderService.get();
    }


    /**
     * 限流后 的逻辑
     * @param e
     * @return
     */
   /* public Map queryFail(int id,BlockException e) {
        System.out.println("---------限流处理");
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "当前服务器忙，请稍后再试！");
        return map;
    }*/

    /**
     * 异常降级处理
     *
     * @param
     * @param
     * @return
     */
    /*public Map handlerError(int id, Throwable e) {
        System.out.println("---------fallback----");
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "服务器异常:" + e.getMessage());
        return map;
    }*/

    @PostConstruct//在类实例化 调用  且调用一次;指定资源的限流规则
    public void init()
    {
        List<FlowRule> ruleList = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("订单");//给指定的资源设置规则
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//设置阈值类型  qps
        rule.setCount(1);//阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式 默认直接
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果 默认直接拒绝
        ruleList.add(rule);
        FlowRuleManager.loadRules(ruleList);//加载流控规则
    }
}
